﻿using System;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Data.Linq;

namespace FlowersStore
{
    public partial class _Default : System.Web.UI.Page
    {
        protected String MenuState;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack) return;
            Int32 CategoryId;
            FillMainMenu();
            if (Request.QueryString["category"] != null)
                if (!Int32.TryParse(Request.QueryString["category"], out CategoryId))
                {
                    using (FlowerStoreDataContext db = new FlowerStoreDataContext())
                    {
                        var cat = (from c in db.Categories
                                   select c).FirstOrDefault();
                        if (cat != null)
                            Response.Redirect("default.aspx?category=" + cat.Category_id.ToString());
                        else
                        {

                            Response.Redirect("default.aspx");
                        }
                    }
                }
                else
                {
                    // запросили категорию CategoryId
                    if (ListView_Products.FindControl("LabelCat") != null)
                    {
                        FlowerStoreDataContext db = new FlowerStoreDataContext();
                        var Category =
                            (from c in db.Categories where c.Category_id == CategoryId select c).SingleOrDefault();
                        if (Category == null)
                            Response.Redirect("default.aspx");
                        ListView_Products.DataBind();
                        ((Label)ListView_Products.FindControl("LabelCat")).Text = Category.Category_name;
                        int num = (from c in db.CategoryProductM2Ms where c.Category_id == CategoryId select c).Count();
                        ((Label)ListView_Products.FindControl("LabelNum")).Text = num.ToString();
                    }
                    if (Session["MenuState"] != null)
                    {
                        string str = "" + Session["MenuState"];
                        for (int i = 0; i < str.Length; i++)
                            if (str[i] == '1')
                                TreeViewMainMenu.Nodes[i].Expand();
                    }
                }
            else
            {
                using (FlowerStoreDataContext db = new FlowerStoreDataContext())
                {
                    var cat = (from c in db.Categories
                               select c).FirstOrDefault();
                    if (cat != null)
                        Response.Redirect("default.aspx?category=" + cat.Category_id.ToString());
                    else
                    {

                        Response.Redirect("default.aspx");
                    }
                }
            }
            //((FlowersStore.SiteMaster)this.Master).FillCartItems();

        }

        private void FillMainMenu()
        {
            TreeViewMainMenu.Nodes.Clear();
            DataLoadOptions opts = new DataLoadOptions();
            opts.LoadWith<Department>(d => d.Categories);

            FlowerStoreDataContext db = new FlowerStoreDataContext();
            var depts = (from dep in db.Departments
                         select dep);
            foreach (Department d in depts)
            {
                TreeNode node = new TreeNode(d.Department_name.ToLower());
                node.ImageUrl = "Styles/Images/ArrowMenu2.png";
                TreeViewMainMenu.Nodes.Add(node);
                foreach (Category cat in d.Categories)
                {
                    TreeNode tn = new TreeNode(cat.Category_name, cat.Category_id.ToString());
                    tn.NavigateUrl = "default.aspx" + "?category=" + cat.Category_id;
                    node.ChildNodes.Add(tn);
                }
            }
            TreeViewMainMenu.CollapseAll();
        }

        protected void Page_Unload(object sender, EventArgs e)
        {
        }

        protected void SearchGo(object sender, EventArgs e)
        {
            string[] keyWords = TextBoxSearch.Text.Split();
            StringBuilder sb = new StringBuilder();
            foreach (string keyWord in keyWords)
                sb.Append(keyWord + "+");
            Response.Redirect("Search.aspx?keywords=" + sb.ToString().TrimEnd('+'));
        }


        protected void TreeViewMainMenu_SelectedNodeChanged(object sender, EventArgs e)
        {
            var treeView = sender as TreeView;
            if (treeView == null) return;
            var node = treeView.SelectedNode;
            if (node == null) return;
            if (node.Parent == null)
                switch (node.Expanded)
                {
                    case true:
                        node.Collapse();
                        break;
                    case false:
                        node.Expand();
                        break;
                }
            var sb = new StringBuilder();
            for (var j = 0; j < treeView.Nodes.Count; j++)
            {
                sb.Append(treeView.Nodes[j].Expanded == true ? "1" : "0");
            }
            Session["MenuState"] = sb.ToString();
            treeView.SelectedNode.Selected = false;
        }

        protected void btnInCart_Click(object sender, EventArgs e)
        {
            long productId = long.Parse(((ImageButton)sender).CommandArgument);
            if (Session["cart"] == null)
                Session["cart"] = new UserCart();
            UserCart cart = (UserCart)Session["cart"];
            cart.AddPosition(productId, 1);
            ((FlowersStore.SiteMaster)this.Master).FillCartItems();
        }

        //void FillCartItems()
        //{
        //    int productsCount = 0;
        //    decimal totalPrice = 0;
        //    if (Session["cart"] != null)
        //    {
        //        UserCart cart = (UserCart)Session["cart"];
        //        productsCount = cart.GetProductsCount();
        //        totalPrice = cart.ComputeTotalPrice();
        //    }
        //    Label lbProducts = (Label)Master.FindControl("lblProductsInCart");
        //    lbProducts.Text = productsCount.ToString();
        //    Label lbTotalPrice = (Label)Master.FindControl("lblTotalPrice");
        //    lbTotalPrice.Text = string.Format("{0:n0}", totalPrice);
        //}


        protected void SortByPrice(object sender, ListViewSortEventArgs e)
        {

            ImageButton btnTop = (ImageButton)ListView_Products.FindControl("btnTop");
            ImageButton btnBottom = (ImageButton)ListView_Products.FindControl("btnBottom");
            switch (e.SortDirection)
            {
                case SortDirection.Ascending:
                    btnBottom.ImageUrl = btnTop.ImageUrl = "Styles/Images/gtk-sort-descending.png";
                    btnBottom.ToolTip = btnTop.ToolTip = "По убыванию цены";
                    break;
                case SortDirection.Descending:
                    btnBottom.ImageUrl = btnTop.ImageUrl = "Styles/Images/view-sort-ascending.png";
                    btnBottom.ToolTip = btnTop.ToolTip = "По возрастанию цены";
                    break;
            }
        }
    }
}
